<!--
 * @Author: toString muzi_li0323@163.com
 * @Date: 2024-05-22 20:22:04
 * @LastEditors: toString muzi_li0323@163.com
 * @LastEditTime: 2024-05-23 19:58:24
 * @FilePath: /chain-link-api-front-admin/src/views/login/index.vue
 * @Description: Login
-->
<template>
  <div class="container block login">
    <div class="loginBox">
      <div class="login-title">
        {{ $t('login.SignIn') }}
      </div>
      <el-form :model="forms" ref="ruleRef" label-width="auto" :rules="rules" label-position="top">
        <el-form-item :label="$t('global.UserName')" prop="username" style="width: 100%">
          <el-input v-model.trim="forms.username" :placeholder="$t('global.PleaseInputUserName')"
                    style="border-radius: 30px"></el-input>
        </el-form-item>
        <el-form-item :label="$t('global.PassWord')" prop="password" style="width: 100%;">
          <el-input v-model.trim="forms.password" :type="inpType" :placeholder="$t('global.PleaseInputPassWord')"
                    @keyup.enter="handleEnter">
            <template #suffix>
              <svg class="icon eyeopen" aria-hidden="true" @click="checkPass" v-show="!eye">
                <use xlink:href="#icon-eye-lined"></use>
              </svg>
              <svg class="icon eyeclose" aria-hidden="true" @click="checkPass" v-show="eye">
                <use xlink:href="#icon-eye-close-lined"></use>
              </svg>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="codeInputVisible" prop="code" :label="'验证码'" style="width: 100%;">
          <el-input v-model.trim="forms.code"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit" :loading="loading" >{{ $t('home.Login') }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRouter} from 'vue-router';
import {useUserStore} from "@/stores";
import {ElMessage} from "element-plus";
import { login, getEmailCodeApi } from '@/require/api.js'
import {useI18n} from "vue-i18n";
const {t} = useI18n();

const footerType = ref('login')
const loading = ref(false)
const locationHref = ref('');
locationHref.value = window.location.href;
const router = useRouter();
const userStore = useUserStore();
const eye = ref(true)
const ruleRef = ref(null);

const rules = reactive({
  username: [{required: true, message: t('message.UserNameIsNull'), trigger: 'blur'}],
  password: [
    {required: true, message: t('message.PWDIsNull'), trigger: 'blur'},
    {min: 8, max: 16, message: t('message.PWDLength'), trigger: 'blur'},
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,16}$/,
      message: t('message.PWDAa09'), trigger: 'blur'
    }
  ],
})

// 验证码输入框默认隐藏
const codeInputVisible = ref(false);

const forms = reactive({
  username: '',
  password: '',
  email: '',
  code: '',
})

// 登录方法
async function submit() {
    try {
      loading.value = true;
      if (forms.username === "" || forms.password === "") {
        ElMessage.error(t("message.InputAll"));
        return;
      }
      const {code, data, msg} = await login({
        userName: forms.username,
        password: forms.password,
        code: forms.code || null,
      });
      if (code === 200) {
        console.log(data)
        ElMessage.success(t('message.LoginSuccess'))
        userStore.setToken(data.token);
        userStore.setUserInfo(data);
        userStore.setAddress(data.address)
        router.push('/layout/userManagement');
      } else if (code === 21103) {
        // 不同 IP 地址登录，返回 21103
        // 弹出验证码输入框
        codeInputVisible.value = true;
        ElMessage.success(t('message.GetCodeSuccess'));
        forms.email = data;
        await getEmailCode();
      } else {
        ElMessage.error(msg);
      }
    }catch (e) {
      console.log(e)
    }finally {
      loading.value = false;
    }
}

// 获取邮箱验证码
async function getEmailCode() {
  try {
    const formData = new FormData();
    formData.append('to', forms.email);
    await getEmailCodeApi(formData);
  } catch (error) {
    console.log('getEmailCodeApi - error', error);
  }
};

// 在输入密码的 input 按下回车键
const handleEnter = () => {
  submit();
};

// 隐藏密码方法
const inpType = ref('password');
const checkPass = () => {
  eye.value = !eye.value;
  inpType.value = inpType.value === 'password' ? 'text' : 'password';
}
</script>

<style scoped lang="less">
//element plus样式 start
.el-form {
  :deep(.el-select__wrapper) {
    height: .42rem;
    border-radius: 8px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
  }

  :deep(.el-input) {
    height: .42rem;
  }

  :deep(.el-button) {
    //background-color: #05aa69;
    //border-color: #05aa69;
    border-radius: 8px;
    width: 3rem;
    height: .42rem;
    color: #fff;
  }
}

.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

//element plus样式 end

/****** 底部“简体中文按钮” ******/
.simpleChinese.is-text:not(.is-disabled):focus-visible {
  outline: none;
}


.login {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  //height: 4rem;
  background: url(@/assets/images/login/loginBg.svg) 100% no-repeat;
  background-size: cover;
}

.loginBox {
  border: 1px solid #e5e5e5;
  border-radius: 5%;
  padding: .1rem;
  box-sizing: border-box;
}

</style>
